<template>
  <div class="ranking-table-container">
    <div class="ranking-header">
      <!-- <span>软科中国大学排名</span> -->
      <div class="ranking-filters">
        <el-input
          v-model="searchQuery"
          placeholder="搜索学校名称、地区或类型"
          size="small"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix><i class="ri-search-line"></i></template>
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>
      <div class="ranking-actions">
        <el-button v-if="schools.length > 0" type="danger" size="small" @click="clearSelectedSchools" plain>
          清除已选学校
        </el-button>
        <el-button type="primary" size="small" @click="changeShowAllSchools" plain>
          {{ showAllSchools ? "显示已选学校" : "显示所有学校" }}
        </el-button>
      </div>
    </div>

    <div class="ranking-table-wrapper">
      <el-table
        ref="rankingTableRef"
        :data="paginatedData"
        style="width: 100%"
        height="calc(100% - 10px)"
        size="small"
        lazy
        row-key="name"
        border
        stripe
        @select="handleSelect"
        @select-all="handleSelectAll"
      >
        <el-table-column type="selection" width="30" fixed="left" />
        <el-table-column prop="rank" label="排名" min-width="70" align="center" sortable>
          <template #default="{ row }">
            <div class="rank-cell" :class="getRankClass(row.rank)">
              {{ row.rank ? row.rank : "500+" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="学校名称" min-width="90">
          <template #default="{ row }">
            <div class="school-name-cell">
              <span>{{ row.name }}</span>
              <!-- <el-tag v-if="row.isSelected" size="small" type="success">已选择</el-tag> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="地区" min-width="60" />
        <el-table-column prop="type" label="类型" min-width="60" />
        <el-table-column label="近四年录取分数" min-width="300">
          <template #default="{ row }">
            <div class="score-history">
              <div class="score-item">
                <span class="year">2024</span>
                <span class="score" :class="{ 'no-data': !row.score_2024 }">{{ row.score_2024 || "暂无数据" }}</span>
              </div>
              <div class="score-item">
                <span class="year">2023</span>
                <span class="score" :class="{ 'no-data': !row.score_2023 }">{{ row.score_2023 || "暂无数据" }}</span>
              </div>
              <div class="score-item">
                <span class="year">2022</span>
                <span class="score" :class="{ 'no-data': !row.score_2022 }">{{ row.score_2022 || "暂无数据" }}</span>
              </div>
              <div class="score-item">
                <span class="year">2021</span>
                <span class="score" :class="{ 'no-data': !row.score_2021 }">{{ row.score_2021 || "暂无数据" }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="总分" min-width="60" />
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[25, 50, 100]"
          :total="filteredRankings.length"
          size="small"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from "vue"
import collegesInfo from "@/assets/colleges-info.json"

interface Props {
  schools?: string[]
  provinces?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  schools: () => [],
  provinces: () => []
})

const emit = defineEmits<{
  (e: "update:schools", val: string[]): void
  (e: "update:provinces", val: string[]): void
}>()

const schools = computed({
  get: () => props.schools,
  set: val => {
    emit("update:schools", val)
  }
})

const provinces = computed({
  get: () => props.provinces,
  set: val => {
    emit("update:provinces", val)
  }
})

const rankingTableRef = ref<any>(null)

const isUpdatingSelection = ref(false) // 标志位，用于防止无限循环更新
const showAllSchools = ref(true) // 标志位，用于控制是否显示所有学校

/* ======================= 搜索查询 ======================= */

// 搜索查询
const searchQuery = ref("")
const filteredRankings = ref<Record<string, any>[]>([])
const selectRow = ref<Record<string, any>[]>([])

// 处理搜索
const handleSearch = () => {
  const rankingData = collegesInfo as Record<string, any>[]
  let filteredData = rankingData

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filteredData = rankingData.filter(
      item =>
        item.name.toLowerCase().includes(query) ||
        item.location.toLowerCase().includes(query) ||
        item.type.toLowerCase().includes(query)
    )
  }

  if (!showAllSchools.value) {
    filteredData = filteredData.filter(item => props.schools.includes(item.name))
  }

  if (filteredData.length === 0) {
    showAllSchools.value = true
  }

  filteredRankings.value = filteredData

  nextTick(() => {
    updateTableSelection()
  })
}

// 监听showAllSchools变化，更新表格选择状态
watch(
  () => showAllSchools.value,
  () => {
    searchQuery.value = ""
    handleSearch()
  }
)

// 监听schools变化，更新表格选择状态
watch(
  () => props.schools,
  () => {
    // 如果是由内部更新触发的，则跳过
    if (isUpdatingSelection.value) return
    handleSearch()
  },
  { deep: true }
)

// 更新表格选择状态
const updateTableSelection = () => {
  if (!rankingTableRef.value) return

  // 设置标志位，防止触发watch
  isUpdatingSelection.value = true

  // 先清除所有选择
  rankingTableRef.value.clearSelection()

  nextTick(() => {
    // 重新选择已选中的学校
    schools.value.forEach(schoolName => {
      const row = filteredRankings.value.find(item => item.name === schoolName)
      if (row) {
        rankingTableRef.value.toggleRowSelection(row, true)
      }
    })
  })

  // 重置标志位
  setTimeout(() => {
    isUpdatingSelection.value = false
  }, 0)
}

const handleSelect = (rows: any[], row: any) => {
  let selected = rows.length && rows.indexOf(row) !== -1
  if (!selected) {
    // 取消选中时，从schools.value中删除对应的元素
    schools.value = schools.value.filter(item => item !== row.name)
    selectRow.value = selectRow.value.filter(item => item !== row)

    // 检查该地区是否还有其他选中的学校
    const hasOtherSchoolsInSameLocation = schools.value.some(schoolName => {
      const school = rows.find(item => item.name === schoolName)
      return school && school.location === row.location
    })

    // 只有当该地区没有其他选中的学校时，才从provinces中移除
    if (!hasOtherSchoolsInSameLocation) {
      provinces.value = provinces.value.filter(item => item !== row.location)
    }
  } else {
    // 选中时，将对应的元素添加到schools.value中
    selectRow.value = [...selectRow.value, row]
    schools.value = [...schools.value, row.name]
    // 如果该地区不在provinces中，则添加
    if (!provinces.value.includes(row.location)) {
      provinces.value = [...provinces.value, row.location]
    }
  }
}

const handleSelectAll = (rows: any[]) => {
  if (rows.length) {
    // 添加选中的学校
    schools.value = [...rows.map(item => item.name), ...schools.value]
    selectRow.value = [...rows, ...selectRow.value]
    // 获取所有选中的学校的地区
    const selectedLocations = [...new Set(rows.map(item => item.location))]
    provinces.value = [...selectedLocations, ...provinces.value]
  } else {
    // 获取当前页所有学校的地区
    const currentPageLocations = paginatedData.value.map(item => item.location)
    // 从selectRow.value 中移除
    selectRow.value = selectRow.value.filter(row => {
      return !paginatedData.value.some(item => item.name === row.name)
    })
    // 从schools中移除当前页的学校
    schools.value = schools.value.filter(schoolName => {
      return !paginatedData.value.some(item => item.name === schoolName)
    })

    // 检查每个地区是否还有选中的学校
    currentPageLocations.forEach(location => {
      const hasOtherSchoolsInSameLocation = schools.value.some(schoolName => {
        const school = selectRow.value.find(item => item.name === schoolName)
        return school && school.location === location
      })

      // 如果该地区没有其他选中的学校，则从provinces中移除
      if (!hasOtherSchoolsInSameLocation) {
        provinces.value = provinces.value.filter(item => item !== location)
      }
    })
  }
}

// 清除已选学校
const clearSelectedSchools = () => {
  // 设置标志位，防止触发watch
  isUpdatingSelection.value = true
  showAllSchools.value = true

  schools.value.splice(0)
  provinces.value.splice(0)
  // 清除表格选择状态
  if (rankingTableRef.value) {
    rankingTableRef.value.clearSelection()
  }

  // 重置标志位
  setTimeout(() => {
    isUpdatingSelection.value = false
  }, 0)
}

const changeShowAllSchools = () => {
  // 设置标志位，防止触发watch
  isUpdatingSelection.value = true
  showAllSchools.value = !showAllSchools.value
  // 重置标志位
  setTimeout(() => {
    isUpdatingSelection.value = false
  }, 0)
}

// 获取排名类名
const getRankClass = (rank: number | string) => {
  const rankNumber = Number(rank)
  if (rankNumber === 1) return "top-1"
  if (rankNumber === 2) return "top-2"
  if (rankNumber === 3) return "top-3"
  return ""
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(25)

// 分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRankings.value.slice(start, end)
})

// 处理页码改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  updateTableSelection()
}

// 处理每页显示数量改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  updateTableSelection()
}

// 监听filteredRankings变化，重置页码
watch(filteredRankings, () => {
  currentPage.value = 1
})

// 初始化数据
onMounted(() => {
  handleSearch()
})
</script>

<style lang="scss" scoped>
.ranking-table-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;

  .ranking-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2px;
    padding: 0 10px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .ranking-filters {
      display: flex;
      gap: 2px;
      align-items: center;
    }
  }

  .ranking-table-wrapper {
    flex: 1;
    max-height: calc(100% - 1px);
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .pagination-container {
      padding: 2px 0;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.rank-cell {
  width: 30px;
  height: 30px;
  line-height: 28px;
  font-size: 12px;
  text-align: center;
  border-radius: 50%;
  margin: 0 auto;
  font-weight: 500;

  &.top-1 {
    color: white;
    font-weight: bold;
    background-color: #f56c6c;
  }

  &.top-2 {
    color: white;
    font-weight: bold;
    background-color: #e6a23c;
  }

  &.top-3 {
    color: white;
    font-weight: bold;
    background-color: #409eff; // 蓝色 - 第三名
  }
}

.school-name-cell {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.score-history {
  display: flex;
  gap: 8px;
  justify-content: space-between;
  padding: 0 5px;

  .score-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;

    .year {
      font-size: 10px;
      color: #909399;
    }

    .score {
      font-size: 8px;
      font-weight: 500;
      color: #409eff;

      &.no-data {
        color: #909399;
        font-size: 8px;
      }
    }
  }
}

:deep(.selected-row) {
  background-color: rgba(103, 194, 58, 0.1) !important;

  &:hover {
    background-color: rgba(103, 194, 58, 0.2) !important;
  }
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;

  th {
    background-color: var(--el-table-header-bg-color);
    color: #606266;
    font-weight: 600;
  }
}
</style>
